/*
 * TUIOEventDispatcher.cpp
 *
 *  Created on: Aug 18, 2010
 *      Author: Ry
 */

#include <stdexcept>
#include <iostream>
#include "TUIOEventDispatcher.h"

using namespace std;
using namespace TUIO;

TUIOEventDispatcher::TUIOEventDispatcher() {
	tuioClient = new TuioClient();
	tuioClient->addTuioListener(this);
	tuioClient->connect();
}

void TUIOEventDispatcher::addTuioObject(TuioObject *tobj) {
}

void TUIOEventDispatcher::updateTuioObject(TuioObject *tobj) {
}

void TUIOEventDispatcher::removeTuioObject(TuioObject *tobj) {
}

void TUIOEventDispatcher::addTuioCursor(TuioCursor *tcur) {
	TUIOEvent event;
	event.type = TUIOEvent::TUIO_ADD_CURSOR;
	event.cursorId = tcur->getSessionID();
	event.x = tcur->getX();
	event.y = tcur->getY();
	events.push_back(event);
}

void TUIOEventDispatcher::updateTuioCursor(TuioCursor *tcur) {
	TUIOEvent event;
	event.type = TUIOEvent::TUIO_UPDATE_CURSOR;
	event.cursorId = tcur->getSessionID();
	event.x = tcur->getX();
	event.y = tcur->getY();
	events.push_back(event);
}

void TUIOEventDispatcher::removeTuioCursor(TuioCursor *tcur) {
	TUIOEvent event;
	event.type = TUIOEvent::TUIO_REMOVE_CURSOR;
	event.cursorId = tcur->getSessionID();
	event.x = tcur->getX();
	event.y = tcur->getY();
	events.push_back(event);
}

void TUIOEventDispatcher::refresh(TuioTime ftime) {

}

TUIOEventHandler* TUIOEventDispatcher::add(TUIOEventHandler *handler) {
	handlers.push_back(handler);
	return handler;
}

void TUIOEventDispatcher::dispatchEvents(float dts) {
	tuioClient->lockCursorList();
	tuioClient->lockObjectList();
	for (unsigned int i = 0; i < events.size(); i++) {
		for (unsigned int j = 0; j < handlers.size(); j++) {
			handlers[j]->setEvent(events[i]);
			handlers[j]->handleEvent(dts);
		}
	}
	events.clear();
	tuioClient->unlockObjectList();
	tuioClient->unlockCursorList();
}

TUIOEventDispatcher::~TUIOEventDispatcher() {
	if (tuioClient->isConnected()) {
		tuioClient->disconnect();
	}
	delete tuioClient;
}
